package Thread_;

class Test{
    public int count1;
    public  void add(){
        synchronized(this){
          count1++;
        }
    }
//    public static int count2;
//   synchronized public static  void add1(){
//          count2++;
//    }
}
public class Thread13 {
    //线程安全问题
    public static void main5(String[] args) throws InterruptedException {
//        Object block = new Object();
        Test test = new Test();
        Thread t1=new Thread(()->{
            for(int i=1;i<=10000;i++){
                test.add();//将count++放到类的方法中，对该类进行加锁
            }
        });
        Thread t2=new Thread(()->{
            for(int i=1;i<=10000;i++){
                test.add();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count="+test.count1);
    }
    private static int count;
    public static void main6(String[] args) throws InterruptedException {
        Object block = new Object();
        Thread t1=new Thread(()->{
            for(int i=0;i<=5000;i++){
                synchronized(block){
                    count+=i;
                }
            }
        });
        Thread t2=new Thread(()->{
            for(int i=5001;i<=10000;i++){
                count+=i;
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count="+count);

    }
    public static void main3(String[] args) throws InterruptedException {
        Object block = new Object();
        Object block2 = new Object();
        Thread t1=new Thread(()->{
            for(int i=0;i<=5000;i++){
                synchronized(block){
                    count+=i;
                }
            }
        });
        Thread t2=new Thread(()->{
            for(int i=5001;i<=10000;i++){
                synchronized(block2){
                    count+=i;
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count="+count);

    }
    public static void main4(String[] args) throws InterruptedException {
        Object block = new Object();
        Thread t1=new Thread(()->{
            for(int i=0;i<=5000;i++){
                synchronized(block){
                    count+=i;
                }
            }
        });
        Thread t2=new Thread(()->{
            for(int i=5001;i<=10000;i++){
                synchronized(block){
                    count+=i;
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count="+count);

    }
    public static void main2(String[] args) throws InterruptedException {
        Thread t=new Thread(()->{
            for(int i=0;i<=10000;i++){
                count+=i;
            }
        });
        t.start();
         t.join();
        System.out.println("count="+count);

    }
}
